package com.smile.cloud.common.base.exception;

import com.smile.cloud.common.base.result.CommonResult;
import com.smile.cloud.common.base.result.BaseResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.xml.bind.ValidationException;
import java.util.stream.Collectors;

/**
 * 基础统一异常处理
 *
 * @author LGC
 */
@Slf4j
public class BaseExceptionHandler {

    /**
     * 参数验证 和 参数绑定验证
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    public CommonResult<Void> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return CommonResult.failed(BaseResultEnum.VALIDATE, message);
    }

    /**
     * 处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数验证失败", e);
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(
                Collectors.joining());
        return CommonResult.failed(BaseResultEnum.VALIDATE, message);
    }

    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     */
    @ExceptionHandler(BindException.class)
    public CommonResult<String> bindExceptionHandler(BindException e) {
        log.error("参数绑定失败", e);
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(
                Collectors.joining());
        return CommonResult.failed(BaseResultEnum.VALIDATE, message);
    }

    /**
     * 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public CommonResult<String> constraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error("参数验证失败", e);
        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        return CommonResult.failed(BaseResultEnum.VALIDATE, message);
    }

    /**
     * 处理缺少参数的请求数据,偶现BUG.在param中request=true出现  警惕:不要将HttpServletRequest传递到任何异步方法中
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public CommonResult<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("处理缺少参数的请求数据", e);
        return CommonResult.failed(BaseResultEnum.VALIDATE, e.getMessage());
    }

    /**
     * 处理请求数据时,没有对参数进行Json序列化
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public CommonResult<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("参数解析失败,没有对参数进行Json序列化", e);
        return CommonResult.failed(BaseResultEnum.VALIDATE, e.getMessage());
    }


    /**
     * 请求Dto,错误的属性配置 如@Size(min = 10, max = 6, message = "验证码长度应该在4-6位之间")
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public CommonResult<String> handleValidationException(ValidationException e) {
        log.error("参数验证失败", e);
        return CommonResult.failed(BaseResultEnum.VALIDATE, e.getMessage());
    }

    /**
     * 请求方法错误
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public CommonResult<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持当前请求方法", e);
        return CommonResult.failed(BaseResultEnum.VALIDATE, e.getMessage());
    }

    /**
     * 415 - Unsupported Media Type 缺少"application/json;charset=UTF-8"类型的数据
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public CommonResult<String> handleHttpMediaTypeNotSupportedException(Exception e) {
        log.error("不支持当前媒体类型", e);
        return CommonResult.failed(BaseResultEnum.VALIDATE, e.getMessage());
    }

    /**
     * 全部异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e) {
        log.error("全部异常:", e);
        return CommonResult.failed(BaseResultEnum.FAILURE);
    }
}
